package org.jl.main;

import org.jl.main.model.User;
import org.jl.main.util.UtilForCollection;
import org.jl.main.util.UtilForJson;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Jackson
 */
public class Main04_1_Jackson {

    /*
    构建对象
     */
    public static void main0(String[] args) {
//        ObjectMapper mapper = new ObjectMapper();
//        ObjectNode node1 = mapper.createObjectNode();
        Map<String, Object> node1 = new LinkedHashMap<>();
        node1.put("userCode", "0001");
        node1.put("userName", "张三");
        String jsonStr1 = UtilForJson.toString(node1);
        System.out.println("json string = " + jsonStr1);
        //格式化打印
        String jsonStr2 = UtilForJson.toString(node1, true, false);
        System.out.println("json string = " + jsonStr2);

//        ArrayNode array1 = mapper.createArrayNode();
        List<Map<String, Object>> array1 = new ArrayList<>();
//        ObjectNode node2 = mapper.createObjectNode();
        Map<String, Object> node2 = new LinkedHashMap<>();
        node2.put("userCode", "0002");
        node2.put("userName", "李四");
        UtilForCollection.of(array1, node1, node2);
        String jsonStr3 = UtilForJson.toString(array1);
        System.out.println("array1 string = " + jsonStr3);
    }

    /*
    对象
     */
    public static void main1(String[] args) {
        User u1 = User.builder().userCode("0001").userName("张三").userAge(18).build();
        String u2Str = "{\"userCode\":\"0002\",\"userName\":\"李四\",\"userAge\":18}";

        //默认驼峰命名规则
        //对象转字符串
        String u1Str = UtilForJson.toString(u1);
        System.out.println("u1 json string = " + u1Str + "\n");

        //字符串转JSON对象
        Map<String, Object> u2Obj = UtilForJson.toMap(u2Str);
        System.out.println("u2 obj = " + u2Obj + "\n");

        //字符串转对象
        //注：readValue方法要求对象必须有无参构造函数
        User u2 = UtilForJson.toBean(u2Str, User.class, false);
        System.out.println("u2 = " + u2 + "\n");

        boolean underline = true;
        //对象转字符串
        String u1Str2 = UtilForJson.toString(u1, false, underline);
        System.out.println("u1 json string = " + u1Str2 + "\n");

        //字符串转对象
        //注：字符串中的属性转换后在对象中不能不存在；字符串中不能有驼峰命名的属性
        User u4 = UtilForJson.toBean(u1Str2, User.class, underline);
        System.out.println("u4 = " + u4 + "\n");

    }

    /*
    数组
     */
    public static void main2(String[] args) {
        //列表转字符串
        String user1Str = UtilForJson.toString(Main02_2_Collection.USERS1);
        System.out.println("users1 json string = " + user1Str + "\n");

        //字符串转列表
        List<User> users1 = UtilForJson.toList(user1Str);
        System.out.println("users1 = " + users1 + "\n");
    }

}
